export class MyWebSocket {
    private socket: WebSocket|null
    private msgCallback:(event:MessageEvent)=>void
    private internal:any;
    //初始化websocket
    constructor(realURL:string,token: string,callback:(event:MessageEvent)=>void) {
        this.msgCallback = callback;
        if("WebSocket" in window){
            this.socket=new WebSocket(`${realURL}/notice/ws/socket?SESSION_TOKEN_KEY=${token}`);
        }else{
            console.error("WebSocket not supported");
            showNotify({
                type:'warning',
                message:'浏览器版本过低，不能使用聊天功能',
                duration:3000
            })
            this.socket=null
        }
        // 关闭事件
        this.socket?.addEventListener('close', this.onClose.bind(this));

        // 连接成功事件
        this.socket?.addEventListener('open', this.onOpen.bind(this));

        // 连接出错事件
        this.socket?.addEventListener('error', this.onError.bind(this));

        // 收到消息事件
        this.socket?.addEventListener('message',this.onMessage.bind(this))
        console.log('开启心跳检查和自动重连……')
        this.internal=setInterval(()=>{
            if(this.socket?.readyState===3){
                const load=showLoadingToast({
                    message:'重新连接……',
                    duration:0
                })
                this.socket=new WebSocket(`${realURL}/notice/ws/socket?SESSION_TOKEN_KEY=${token}`);
                load.close()
            }
        },3000)
    }
    private onClose(event: CloseEvent): void {
        console.log('WebSocket closed', event);
    }

    private onOpen(event: Event): void {
        console.log('WebSocket connected', event);
    }

    private onError(event: Event): void {
        console.error('WebSocket error', event);
    }
    //接收消息后的逻辑
    private onMessage(event: MessageEvent): void {
        this.msgCallback(event)
        // console.log('WebSocket message:', event.data);
        // if(!useRoute().path.includes('chat')) showToast('您有新的消息待查看')
    }
    // 获取websocket对象
    getWebSocket():WebSocket|null {
        return this.socket;
    }
    sendMessage(message:string):boolean {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(message);
            return true;
        } else {
            console.error('WebSocket is not open');
            return false;
        }
    }
    getInternal():any {
        return this.internal
    }
    setMsgCallback(callback:(e:MessageEvent)=>void) {
        this.msgCallback=callback
    }
}